﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
using LunchCommand.Data;
using LunchCommand.Models;
using LunchCommand.Models.Logging;
using System.Diagnostics;
using System.Reflection;

namespace LunchCommand.Controllers
{
    public abstract class BaseController : Controller
    {
        private Boolean skipUserCheck = false;

        protected BaseController()
        {

        }

        protected BaseController(bool skipUserCheck)
        {
            this.skipUserCheck = skipUserCheck;
        }

        protected ILogger Logger { get; set; }

        protected User LunchUser { get; set; }

        protected LunchCommandContext DatabaseContext { get; set; }

        protected WebConfigSettings Settings { get; private set; }

        protected override void Initialize(RequestContext context)
        {
            base.Initialize(context);

            this.DatabaseContext = context.HttpContext.ApplicationInstance.AsLcAppication().DatabaseContext;
            this.Logger = new DatabaseLogger(new LogRepository(this.DatabaseContext));
            this.Settings = WebConfigSettings.CreateFrom(WebConfigurationManager.AppSettings);

            var userName = context.HttpContext.User.Identity.Name;

            var user = this.DatabaseContext.Users.Where(u => u.WindowsUsername.Equals(userName)).FirstOrDefault();

            if (user == null)
            {
                user = this.DatabaseContext.Users.Add(new User()
                {
                    WindowsUsername = userName,
                    Name = userName
                });
            }
            else
            {
                user.LastActionTime = DateTime.Now;
            }

            this.DatabaseContext.SaveChanges();
            this.LunchUser = user;

            this.ViewBag.LunchUser = user;
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!this.skipUserCheck)
            {
                if (this.LunchUser.Name.Equals(this.LunchUser.WindowsUsername))
                {
                    filterContext.Result = this.RedirectToAction("Edit", "Users");
                }
                else
                {
                    base.OnActionExecuting(filterContext);
                }
            }

            string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            ViewBag.Version = assemblyVersion;
        }
    }
}